<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/17
 * Time: 10:31
 */
namespace app\home\model;

use app\home\model\Base;
use think\Model;
use think\Request;
use think\Db;
use think\Exception;
use think\Log;
use think\Session;

class Quick extends Base {

    /**
     * 微信用户授权
     */
    public function getAuthUserOpenidM()
    {
        try {
            // 授权回调地址
            $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/home/Quick/index';
            $auth = $this->getAuthUserOpenid($redirect_url);
            return $auth;
        } catch (Exception $e) {
            Log::write('微信用户授权异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 卡片验证规则：
     * 1、已经归属直接客户的卡片
     * 2、已激活、有效期内已停卡的卡片
     */
    public function checkCardM()
    {
        try {
            $param = Request::instance()->param();
            if(!$param['iccid']){
                return ['code'=>1,'msg'=>'请输入续费卡片iccid'];
            }
            $sql = "SELECT a.`id`,a.`iccid`,a.`aid`,a.`cid`,a.`pid`,c.`globalsimtype` FROM yc_agent_card AS a LEFT JOIN yc_card AS c ON a.`iccid` = c.`iccid` ";
            $sql .= " WHERE a.`cid` != '' AND a.`iccid` = '".$param['iccid']."' AND c.`dateexpire` > ".time()." AND c.`status` IN (3,4) LIMIT 1";
            $result = Db::query($sql);
            if(!$result){
                return ['code'=>1,'msg'=>'iccid有误，请核对'];
            }
            return ['code'=>0,'msg'=>'iccid符合续费条件','card'=>$result];
        } catch (Exception $e) {
            Log::write('验证快速续费卡片异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 确认续费
     */
    public function confirmRenewM()
    {
        try {
            // 续费卡片归属用户信息
            $user_info = Session::get('S_N_USER_INFO');
            // 获取微信支付相关配置
//            $get_config = $this->getAdminConfig($user_type = 1, $type = 1);   // 默认获取总后台作为测试用
            $get_config = $this->getAdminConfig($user_type = 2, $type = 1, $user_id = $user_info['agent_id']);   // 获取直接客户对应的代理商配置
            if(!$get_config){
                return ['code'=>6,'msg'=>'暂不支持快速续费'];
            }
            $param = Request::instance()->post();
            $openId = Session::get('S_WX_OPENID');
            if(!$openId){
                return ['code'=>1,'msg'=>'服务器异常！'];
            }
            // 验证续费周期
            if(!in_array($param['cycle'],$this->renew_type)){
                return ['code'=>2,'msg'=>'请选择正确的续费周期'];
            }
            // 验证卡片
            $check = $this->checkCardM();
            if($check['code']){
                return ['code'=>3,'msg'=>'续费失败'];
            }
            // 获取续费的套餐信息
            $package = $this->getCardPackageM($check['card'][0]['pid'],$user_info);
            if($package['code']){
                return ['code'=>4,'msg'=>'续费失败'];
            }
            // 获取续费金额
            $renew_price = $package['package']['pkg_price']*$param['cycle']*100;
            $order_info = [
                'iccid'=>[$check['card'][0]["id"]],  // agent_card中的记录id
                'cycle'=>$param['cycle'],  // 续费周期
                'operator'=>$check['card'][0]['globalsimtype'],  // 运营商
            ];
            $order_type = 13;  // 订单类型 13：快速续费
            $order_source = 2;   // 付款方式 2：微信支付
            $order_status = 2;   // 订单状态 2：未支付
            $order_remarks = '';  // 订单备注
            $express = [];  // 快递信息
            // 验证成功后，生成续费订单
            $create_order = $this->createOrder($renew_price, $order_type, $order_source, json_encode($order_info,JSON_UNESCAPED_UNICODE), $order_status, $order_remarks, $express, $user_info);
            if(!$create_order){  // 订单创建失败,并生成续费记录
                $renew_log = $this->createLog($param['iccid'],'快速续费',false);
                return ['code'=>5,'msg'=>'快速续费失败'];
            }
            // 生成续费记录
            $renew_log = $this->createLog($param['iccid'],'快速续费',true);
            // 获取JSAPI支付的参数
            $JSAPI = array(
                'body'=>'物联网卡快速续费',  // 商品名称
                'out_trade_no'=>$create_order.mt_rand(1000,9999),  // 订单号+4位随机数
                'total_fee'=>$renew_price,
                'spbill_create_ip'=>Request::instance()->ip(),   // 终端ip
                'NotifyUrl'=>"http://".$_SERVER['HTTP_HOST']."/home/Quick/wxNotifyUrl",
                'openid'=>$openId,
            );
            $wx_config = $get_config[0]['data'];  // 微信支付配置
            // 调用微信JSAPI支付，获取相关信息
            vendor('wxpay.Wxpay');
            $wx_pay = new \wxpay\Wxpay($wx_config['app_id'],$wx_config['mch_id'],$wx_config['appsecret'],$wx_config['mch_key']);
            $pay_conf = $wx_pay->GetPrePayMsg($JSAPI);
            if(!$pay_conf){
                return ['code'=>5,'msg'=>'支付异常！'];
            }
            return ['code'=>0,'msg'=>$pay_conf];
        } catch (Exception $e) {
            Log::write('快速续费的异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 处理微信支付回调信息
     * 记录支付信息，验证支付是否成功，进行订单状态的修改
     */
    public function handleWxInfo()
    {
        try {
            $rsv_data = file_get_contents('php://input'); // 获取回调信息
            $result = $this->XmlToArr($rsv_data);  //  XML转数组
            // 记录每次微信回调的信息，并返回订单编号，付款用户id的数组
            $record = $this->recordPayInfo(2,$result);

            // 获取总后台的微信支付配置
            $config = $this->getAdminConfig($user_type = 1, $type = 1);
            $wx_config = $config[0]['data'];
            vendor('wxpay.Wxpay');
            $weixin = new \wxpay\Wxpay($wx_config['app_id'],$wx_config['mch_id'],$wx_config['appsecret'],$wx_config['mch_key']);
            /** 测试数据
                $result = [   // 测试数据
                        "appid"=>"wx8e232630eae3ee02",
                        "bank_type"=>"CMB_CREDIT",
                        "cash_fee"=>"1",
                        "fee_type"=>"CNY",
                        "is_subscribe"=>"Y",
                        "mch_id"=>"1489295902",
                        "nonce_str"=>"32c5914922d5d0aa7471cb9c79304ba2",
                        "openid"=>"oG6VH0TXulLeV7_c6ys1MDJ6hztg",
                        "out_trade_no"=>"Yiot13152661145098611906",
                        "result_code"=>"SUCCESS",
                        "return_code"=>"SUCCESS",
                        "sign"=>"32D9DB820BBD19D8A76B5AF83B6B4CA3",
                        "time_end"=>"20180518104417",
                        "total_fee"=>"1",
                        "trade_type"=>"JSAPI",
                        "transaction_id"=>"4200000125201805182049002001"
                ];
                $record = ['order_number'=>'Yiot1315266114509861','payer'=>'1'];
             */
            if(!$weixin->CheckSign($result)){  // 签名认证失败,返回消息
                $return['return_code'] = 'FAIL';
                $return['return_msg'] = '签名错误';
                $return['sign'] = $weixin->MakeSign($result);
                $return = $weixin->PayArrToXml($return);
                echo $return;
                exit;
            }
            if ($result['result_code'] == "SUCCESS" && $result['return_code'] == "SUCCESS") {
                // 修改订单状态
                $this->editOrderStatus($record);  //  订单编号
                // 返回信息
                $return['return_code'] = 'SUCCESS';
                $return['return_msg'] = 'OK';
                $return['sign'] = $weixin->MakeSign($result);
                $return = $weixin->PayArrToXml($return);
                echo $return;
            }
        } catch (Exception $e) {
            Log::write('处理微信支付回调信息异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 记录支付回调的信息
     * @param int $type 回调信息类型
     * @param array $info 回调信息
     */
    protected function recordPayInfo($type, $info)
    {
        try {
            // 获取付款用户id
            $order_number = substr($info['out_trade_no'], 0, -4);   // 微信支付申请的订单编号是在内部编号后面+四位随机数
            $sql_user = "SELECT `payer` FROM yc_order WHERE `order_number` = '".$order_number."'";
            $user = Db::query($sql_user);
            $payer = $user[0]['payer'];
            $info = json_encode($info);
            $sql = "INSERT INTO yc_pay_log (`pay_type`,`order_number`,`payer`,`data`,`addtime`) VALUES (".$type.",".$order_number.",".$payer.",'".$info."','".time()."')";
            $result = Db::execute($sql);
            return ['order_number'=>$order_number,'payer'=>$payer];
        } catch (Exception $e) {
            Log::write('记录支付回调信息异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 修改订单状态
     * @param array $info 订单编号、付款用户id数组
     * @return  bool true：修改成功；fals：修改失败
     */
    protected function editOrderStatus($info = [])
    {
        try {
            $sql = "UPDATE yc_order SET `status` = 1,`paytime` = ".time()." WHERE `order_number` = '".$info['order_number']."' AND `payer` = ".$info['payer'];
            $result = Db::execute($sql);
            return $result ? true : false;
        } catch (Exception $e) {
            Log::write('快速续费修改订单状态异常：'.$e->getMessage(),'error');
        }
    }

}